package com.yyk.yykywd.ui.customer;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yyk.yykywd.R;
import com.yyk.yykywd.base.BaseFragment;
import com.yyk.yykywd.base.BaseRecyclerAdapter;
import com.yyk.yykywd.base.BaseRecyclerHolder;
import com.yyk.yykywd.http.ApiService;
import com.yyk.yykywd.bean.ClientListInfo;
import com.yyk.yykywd.util.Md5Util2;
import com.yyk.yykywd.util.ToastUtil;
import com.yyk.yykywd.widght.diver.CustomDecoration;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2019/1/16 0016.
 */

public class CustomerList2Fragment extends BaseFragment {
    public static CustomerList2Fragment intance;
    public static final String ARGS_PAGE = "CustomerList2Fragment";
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.smartrefreshlayout)
    SmartRefreshLayout smartrefreshlayout;
    @BindView(R.id.ll_emptyview)
    LinearLayout llEmptyview;


    @BindView(R.id.bt_ckqbfragment)
    TextView btCkqbfragment;
    @BindView(R.id.bt_zkzjfragment)
    TextView btZkzjfragment;
    @BindView(R.id.ll_grade) //是否是领导
            LinearLayout llGrade;

    private String state;
    private int currentPage = 1;
    public static String type = "0"; //"" 查看全部  "1"查看自己


    public static CustomerList2Fragment newInstance(int page) {
        Bundle args = new Bundle();
        args.putInt(ARGS_PAGE, page);
        CustomerList2Fragment fragment = new CustomerList2Fragment();
        fragment.setArguments(args);
        return fragment;
    }

//    /**
//     * TODO 懒加载有问题 搭配 适配器 destory方法好像没事了
//     * 每次点击tab调用数据！！！
//     *
//     * @param isVisible true  不可见 -> 可见
//     */
//    @Override
//    protected void onFragmentVisibleChange(boolean isVisible) {
//        super.onFragmentVisibleChange(isVisible);
//        if (isVisible) {
//            //TODO 在这里处理数据
//            postClientList(true);
//        }else{
//            return;
//        }
//    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_customerlist2_test;
    }

    @Override
    public void initView() {
        initRefresh();
    }

    @Override
    public void initData() {
        intance = this;
        initGetIntent();
        initAdapter();
        postClientList(true);


    }

    private void initRefresh() {
        smartrefreshlayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
                currentPage = 1;
                postClientList(true);
                //禁止点击内容
                smartrefreshlayout.setDisableContentWhenRefresh(true);
                smartrefreshlayout.finishRefresh();
//                    }
//                }, 1500);

            }
        });
        smartrefreshlayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                currentPage++;
                postClientList(false);
                smartrefreshlayout.setDisableContentWhenRefresh(true);
                smartrefreshlayout.finishLoadMore();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        //TODO 在这里处理数据
        postClientList(true);
    }

    private void initGetIntent() {
        //是否是领导，是显示 筛选
        String grade = Hawk.get("grade") + "";
        if (grade.equals("1")) {
            llGrade.setVisibility(View.VISIBLE);
        }

        clearPitcureColor();
        btCkqbfragment.setTextColor(getResources().getColor(R.color.blue_51));
        btCkqbfragment.setBackground(getResources().getDrawable(R.drawable.kehu_yesbluebg));

        Bundle arguments = getArguments();
        state = arguments.getString(CustomerList2Fragment.ARGS_PAGE);
        boolean flagType = arguments.containsKey("type");
        if (flagType) {
            type = arguments.getString("type");
//            if (type.equals("0")) {
//                clearPitcureColor();
//                btCkqbfragment.setTextColor(getResources().getColor(R.color.blue_51));
//                btCkqbfragment.setBackground(getResources().getDrawable(R.drawable.kehu_yesbluebg));
//            } else if (type.equals("1")) {
//                clearPitcureColor();
//                btZkzjfragment.setTextColor(getResources().getColor(R.color.blue_51));
//                btZkzjfragment.setBackground(getResources().getDrawable(R.drawable.kehu_yesbluebg));
//            }
        }
    }

    private List<ClientListInfo.DataBean> list = new ArrayList<>();
    private BaseRecyclerAdapter<ClientListInfo.DataBean> adapter;

    private void initAdapter() {

        adapter = new BaseRecyclerAdapter<ClientListInfo.DataBean>(getActivity(), list, R.layout.adapter_item_customerlist) {
            @Override
            public void convert(BaseRecyclerHolder holder, ClientListInfo.DataBean item, int position, boolean isScrolling) {
                TextView tv_state = holder.getView(R.id.tv_state);
                holder.setText(R.id.tv_hname, item.getHname());
                holder.setText(R.id.tv_name_postname_phone, item.getName() + " | " + item.getPost_name() + " | " + item.getPhone());
                String del = item.getDel();
                if (del.equals("2")) {
                    holder.getView(R.id.tv_name_postname_phone).setVisibility(View.GONE);
                    holder.setText(R.id.tv_state, "计划已删除");
                    tv_state.setTextColor(getResources().getColor(R.color.gray_b3));
                } else {
                    //当判断状态 为 已删除，未拜访:隐藏拜访信息
                    int state = item.getState();
                    if (state == 1) {
                        holder.setText(R.id.tv_state, "未拜访");
                        holder.getView(R.id.tv_name_postname_phone).setVisibility(View.GONE);
                        tv_state.setTextColor(getResources().getColor(R.color.red_e8));

                    } else if (state == 2) {
                        holder.setText(R.id.tv_state, "未拜访");
                        holder.getView(R.id.tv_name_postname_phone).setVisibility(View.GONE);
                        tv_state.setTextColor(getResources().getColor(R.color.red_e8));

                    } else if (state == 3) {
                        holder.setText(R.id.tv_state, "待签合同");
                        holder.getView(R.id.tv_name_postname_phone).setVisibility(View.VISIBLE);
                        tv_state.setTextColor(getResources().getColor(R.color.red_e8));

                    } else if (state == 4) {
                        holder.setText(R.id.tv_state, "待回款");
                        holder.getView(R.id.tv_name_postname_phone).setVisibility(View.VISIBLE);
                        tv_state.setTextColor(getResources().getColor(R.color.red_e8));

                    } else if (state == 5) {
                        holder.setText(R.id.tv_state, "合作成功");
                        holder.getView(R.id.tv_name_postname_phone).setVisibility(View.VISIBLE);
                        tv_state.setTextColor(getResources().getColor(R.color.green_2a));
                    } else if (state == 6) {
                        holder.setText(R.id.tv_state, "仍需跟进");
                        holder.getView(R.id.tv_name_postname_phone).setVisibility(View.VISIBLE);
                        tv_state.setTextColor(getResources().getColor(R.color.red_e8));
                    } else if (state == 7) {
                        holder.setText(R.id.tv_state, "合作未达成");
                        holder.getView(R.id.tv_name_postname_phone).setVisibility(View.VISIBLE);
                        tv_state.setTextColor(getResources().getColor(R.color.red_e8));

                    }
                }
            }
        };
        rvList.addItemDecoration(new CustomDecoration(getActivity(), CustomDecoration.VERTICAL_LIST, R.drawable.divider_f8f_10, 0));
        rvList.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvList.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView parent, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("id", list.get(position).getId() + "");
                startAct(MyCustomerActivity.class, bundle);
            }
        });
    }

    public void rertsh() {
        currentPage = 1;
        postClientList(true);
    }


    /**
     * 接口31:客户列表（whm）
     *
     * @param flag
     */
    public void postClientList(final boolean flag) {
        Map<String, String> map = new TreeMap<>();
        map.put("uid", Hawk.get("uid") + "");
        map.put("state", state + "");
        map.put("limit", "10");
        map.put("page", currentPage + "");
        map.put("name", "");
        if (type.equals("0")) {
            map.put("type", "");
        }
        if (type.equals("1")) {
            map.put("type", "1");
        }
        Logger.d("查看全部+只看自己状态————" + type);
        map.put("sign", Md5Util2.createSign(map));
        ApiService.getInstance().api.postClientList(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(new Observer<ClientListInfo>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ClientListInfo info) {
                        Logger.e("31:第二个客户列表（whm）" + info.toString());
                        if (info.getCode() == 1) {
                            if (flag) {
                                list.clear();
                            }
                            if (info.getData().size() > 0 && info.getData() != null) {
                                list.addAll(info.getData());
                            }
                            adapter.notifyDataSetChanged();
                            if (rvList != null) {
                                rvList.setVisibility(View.VISIBLE);
                            }
                            llEmptyview.setVisibility(View.GONE);
                        } else if (info.getCode() == 2) {
                            if (list.size() > 0) {

                            } else {
                                rvList.setVisibility(View.GONE);
                                llEmptyview.setVisibility(View.VISIBLE);
                            }

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.t("异常" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void clearPitcureColor() {
        btCkqbfragment.setBackground(getResources().getDrawable(R.drawable.kehu_nobluebg));
        btZkzjfragment.setBackground(getResources().getDrawable(R.drawable.kehu_nobluebg));
        btCkqbfragment.setTextColor(getResources().getColor(R.color.black_33));
        btZkzjfragment.setTextColor(getResources().getColor(R.color.black_33));
    }

    /**
     * 1.查看全部
     * 2.只看自己
     * 3.筛选框
     *
     * @param view
     */

    @OnClick({R.id.bt_ckqbfragment, R.id.bt_zkzjfragment, R.id.bt_sxxsfragment})
    public void onViewClicked(View view) {

        switch (view.getId()) {
            case R.id.bt_ckqbfragment:
                //改变子Fragment中变量
                type = "0";
                rertsh();
                list.clear();
                clearPitcureColor();
                btCkqbfragment.setTextColor(getResources().getColor(R.color.blue_51));
                btCkqbfragment.setBackground(getResources().getDrawable(R.drawable.kehu_yesbluebg));
                break;
            case R.id.bt_zkzjfragment:
                //改变子Fragment中变量
                type = "1";
                list.clear();
                rertsh();
                clearPitcureColor();
                btZkzjfragment.setTextColor(getResources().getColor(R.color.blue_51));
                btZkzjfragment.setBackground(getResources().getDrawable(R.drawable.kehu_yesbluebg));
                break;
            case R.id.bt_sxxsfragment:
                ToastUtil.showShort("功能暂未开放");
                break;


        }
    }
}
